﻿using IService.Admin;
using Model.Result.Admin;

namespace Service.Admin
{
    public class AdminPermissionService : BaseService<TPermission>, IAdminPermissionService
    {
        public AdminPermissionService(IUnitOfWorkService se) : base(se)
        {
        }

        public async Task<RM_ApiResult> ActionPowers(List<int> Powers, int AdminKey)
        {
            var isSuper = await Any<TAdminInfo>(o => o.Id == AdminKey && o.IsSuper);
            if (isSuper)
            {
                return _ResultHelper.BuildSuccess();
            }
            else
            {
                _DbContext.Deleteable<TAdminpermissionrelation>().Where(o => o.AdminId == AdminKey).AddQueue();
                Powers.ForEach(item =>
                {
                    _DbContext.Insertable(new TAdminpermissionrelation { AdminId = AdminKey, CreateTime = DateTime.Now, PermissionId = item }).AddQueue();
                });
                try
                {
                    await _DbContext.SaveQueuesAsync<TAdminpermissionrelation>();
                    return _ResultHelper.BuildSuccess();
                }
                catch
                {
                    return _ResultHelper.BuildError();
                }
            }
        }

        public async Task<RM_ApiResult> GetAllPowers(int AdminKey)
        {
            var adminInfo = await Get<TAdminInfo>(AdminKey);
            var isSuper = adminInfo?.IsSuper == true;
            var result = await _DbContext.Queryable<RM_AdminPowers>().Includes(t1 => t1.Children.MappingField(z => z.FatherAuthId, () => t1.Id).ToList())
                                         .Where(o => o.FatherAuthId == 0).ToListAsync();
            var powers = isSuper ? new List<int>() : await _DbContext.Queryable<TAdminpermissionrelation>().Where(o => o.AdminId == AdminKey)
                                         .Select(o => o.PermissionId).ToListAsync();
            result.ForEach(item =>
            {
                item.IsHas = isSuper || powers.Contains(item.Id);
                item.Children.ForEach(child =>
                {
                    child.IsHas = isSuper || powers.Contains(child.Id);
                });
            });
            return _ResultHelper.BuildSuccess(new { datas = result });
        }
    }
}